package com.heyou.ticket.assistant;

import com.heyou.ticket.tools.TicketBookDetailTools;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;
import java.time.LocalTime;

/**
 * HeyouAgent 智能体
 */

@Service
public class HeyouAgent {

    private final ChatClient chatClient;


    // 构造函数 自动装配 ChatClient，并配置默认系统提示、聊天记忆顾问和RAG问题回答顾问
    public HeyouAgent(ChatClient.Builder modelBuilder,
                      VectorStore vectorStore,
                      ChatMemory chatMemory,
                      TicketBookDetailTools ticketBookDetailTools,
                      @Value("classpath:static/heyou-prompt-template.txt") Resource resource) {
        this.chatClient = modelBuilder.defaultUser(resource, StandardCharsets.UTF_8)
                .defaultSystem(resource) // 设置默认系统提示，此处为加载文件中的内容
                .defaultAdvisors( // 设置默认顾问，此处为聊天记忆顾问和 RAG 问题回答顾问
                        new PromptChatMemoryAdvisor(chatMemory),  // 聊天记忆顾问，用于根据聊天历史提供建议
                        new QuestionAnswerAdvisor(vectorStore, SearchRequest.builder().build()) // RAG 问题回答顾问，用于从向量数据库中查找相关信息
                )
                .defaultTools(ticketBookDetailTools) // 设置默认工具，此处为 ticketBookDetailTools
                .build();
    }

    public String chat(String message) {
        // 使用 chatClient 进行聊天，并返回结果
        return this.chatClient.prompt() // 构建一个聊天提示
                .user(message) // 设置用户消息
                .call() // 执行聊天
                .content(); // 获取聊天结果
    }

    public Flux<String> streamChat(String message) {
        return this.chatClient.prompt()
                .user(message)
                .system(pss -> pss.param("current_time", LocalTime.now().toString()))
                .stream()
                .content()
                .concatWith(Flux.just("[complete]"));
    }
}
